package com.android.dx.youzan.meiye;

import android.content.Intent;
import android.net.Uri;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.android.dx.youzan.app.App;
import com.android.dx.youzan.app.Cookies;
import com.android.dx.youzan.meiye.model.Buyer;
import com.android.dx.youzan.meiye.model.ServiceGoods;
import com.blankj.utilcode.util.ActivityUtils;
import com.lg.meng.utils.ClipboardUtils;
import com.lg.meng.utils.ThreadUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class ServiceMain {
    static OkHttpClient okHttpClient = new OkHttpClient();
    static long time;
    static long arriveAt = 0;
    static SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm");

    static {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DATE);

        String str = year + "/" + (month > 9 ? ("" + month) : "0" + month) + "/" + (day > 9 ? ("" + day) : "0" + day) + " 10:00";
        try {
            time = sdf.parse(str).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        ThreadUtils.runOnThread(() -> {
            Cookies cookies = App.getCookie();
            String cookie = cookies.getCookie();

            String _csrf = cookies.get_csrf();
//            String kdtId = "43992027";
//            String deptId = "43991843";
            String kdtId = "43990976";
            String deptId = "43993058";
            arriveAt = time + 15 * 60 * 1000 * (int) (Math.random() * 40);
            arriveAt += ((int) (Math.random() * 10) + 1) * 24 * 60 * 60 * 1000;
            log("随机预约时间：" + sdf.format(arriveAt));
            getBuyerInfo(cookie, _csrf, kdtId, deptId);
        });
    }

    public static void getBuyerInfo(String cookie, String _csrf, String kdtId, String deptId) {
        String url = "https://mei1cxndhebhhhelo.youzan.com/api/h5/mei/customer/buyer/info?_csrf=" + _csrf + "&json="
                + "{\"kdtId\":\"" + kdtId + "\",\"deptId\":\"" + deptId + "\"}";
        Request request = new Request.Builder()
                .get().url(url)
                .addHeader("Cookie", cookie)
                .build();
        try {
            Response execute = okHttpClient.newCall(request).execute();
            Buyer buyer = JSON.parseObject(execute.body().string(), Buyer.class);
            if (buyer.getCode() != 10000) {
                log("获取买家信息失败：" + buyer.getMessage());
                return;
            }
            log("获取买家信息成功：" + buyer.getData().getName() + "," + buyer.getData().getMobile());
            商家服务列表(cookie, _csrf, kdtId, deptId, buyer);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void 商家服务列表(String cookie, String _csrf, String kdtId, String deptId, Buyer buyer) {
        String url = "https://mei1cxndhebhhhelo.youzan.com/api/h5/free/mei/goods/listServingItemByQuery?_csrf=" + _csrf;
        String bodyJson = "{\n"
                + "\t\"json\": \"{\\\"keyword\\\":\\\"\\\",\\\"orderByType\\\":3,\\\"desc\\\":1"
                + ",\\\"pageNo\\\":1,\\\"pageSize\\\":20,\\\"tagId\\\":0,\\\"yzUid\\\":\\\"" + buyer.getData().getYzUid()
                + "\\\",\\\"kdtId\\\":\\\"" + kdtId + "\\\",\\\"deptId\\\":\\\"" + deptId + "\\\"}\"\n"
                + "}";

        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; Charset=utf-8"), bodyJson);
        Request request = new Request.Builder().url(url).post(requestBody)
                .addHeader("Content-Type", "application/json")
                .addHeader("Cookie", cookie)
                .build();
        String string = "";
        try {
            Response response = okHttpClient.newCall(request).execute();
            string = response.body().string();
            JSONObject jsonObject = JSON.parseObject(string);
            if (jsonObject.getInteger("code") == 10000) {
                JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("list");
                log("查询到" + jsonArray.size() + "个商品");
                int goodsIndex = (int) (Math.random() * jsonArray.size());
                JSONObject itemObj = jsonArray.getJSONObject(goodsIndex);
                ServiceGoods goods = JSON.parseObject(itemObj.toJSONString(), ServiceGoods.class);
                log("开始预约第" + (goodsIndex + 1) + "个商品");
                预约(cookie, _csrf, kdtId, deptId, goods, buyer, arriveAt);
            } else {

            }
        } catch (Exception e) {
            e.printStackTrace();
            log(string);
        }

    }

    public static void 预约(String cookie, String _csrf, String kdtId, String deptId, ServiceGoods goods, Buyer buyer, long arriveAt) {
        try {
            String url = "https://cashier.youzan.com/pay/mei/api/mei/reserve/buyer/create_reserve?_csrf=" + _csrf;
            JSONObject jsonObject = new JSONObject();
            JSONArray jsonArray = new JSONArray();
            JSONObject reserveItemObj = new JSONObject();
            reserveItemObj.put("startPoint", arriveAt);
            reserveItemObj.put("itemSnapshotId", goods.getSnapshotId());
            reserveItemObj.put("itemType", 1);
            reserveItemObj.put("itemId", goods.getId());
            reserveItemObj.put("goodsId", goods.getGoodsId());
            reserveItemObj.put("skuId", goods.getDefaultGoodsStock().getSkuId() + "");
            reserveItemObj.put("originPrice", goods.getPrice());
            reserveItemObj.put("num", 1);
            reserveItemObj.put("realPay", goods.getPrice());
            jsonArray.add(reserveItemObj);
            jsonObject.put("reserveItems", jsonArray);
            jsonObject.put("guestMobile", buyer.getData().getMobile());
            jsonObject.put("guestName", buyer.getData().getName());
            jsonObject.put("guestNum", 1);
            jsonObject.put("arriveAt", arriveAt);
            jsonObject.put("remark", "");
            jsonObject.put("kdtId", goods.getKdtId() + "");
            jsonObject.put("deptId", goods.getDeptId() + "");

            JSONObject jsonObjectOuter = new JSONObject();
            jsonObjectOuter.put("json", jsonObject.toJSONString());
            String bodyJson = jsonObjectOuter.toJSONString();
            RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; Charset=utf-8"), bodyJson);
            Request request = new Request.Builder().url(url).post(requestBody).addHeader("Content-Type", "application/json")
                    .addHeader("Cookie", cookie).build();
            OkHttpClient okHttpClient = new OkHttpClient();
            try {
                Response response = okHttpClient.newCall(request).execute();
                String string = response.body().string();
                JSONObject responseObj = JSON.parseObject(string);
                if (responseObj.getIntValue("code") == 200) {
                    String orderNo = responseObj.getJSONObject("data").getString("orderNo");
                    String tradeOrderNo = responseObj.getJSONObject("data").getString("tradeOrderNo");
                    log("预约成功");
                    提交预约(cookie, _csrf, kdtId, deptId, orderNo);
                } else {
                    log("预约失败：" + responseObj.getString("message"));
                }
            } catch (Exception e) {
                e.printStackTrace();
                log("预约失败：" + e.getMessage());
            }
        } catch (Exception e) {
            log("预约失败：" + e.getMessage());
        }
    }

    public static void 提交预约(String cookie, String _csrf, String kdtId, String deptId, String orderNo) {
        //channelType 4:支付宝支付
        String url = "https://cashier.youzan.com/pay/mei/api/mei/pay/buyer/direct_pay?_csrf=" + _csrf
                + "&json={\"orderNo\":\"" + orderNo + "\",\"channelType\":4,\"accountNo\":\"\",\"kdtId\":\"" + kdtId
                + "\",\"deptId\":\"" + deptId + "\"}";
        Request request = new Request.Builder().get().url(url).build();
        try {
            Response execute = okHttpClient.newCall(request).execute();
            String string = execute.body().string();
            JSONObject jsonObject = JSON.parseObject(string);
            if (jsonObject.getIntValue("code") == 200) {
                log("提交预约成功，开始获取支付链接");
                拿支付链接(jsonObject);
            } else {
                log("提交预约失败：" + jsonObject.getString("message"));
                log("提交预约返回" + string);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log("提交预约失败：" + e.getMessage());
        }

    }

    /**
     * 需要禁止重定向，否则响应头中获取不到Location(支付链接)
     */
    public static void 拿支付链接(JSONObject jsonObject) {
        JSONObject dataObj = jsonObject.getJSONObject("data");
        String deepLinkInfo = dataObj.getString("deepLinkInfo");
        JSONObject deepLinkInfoObj = JSON.parseObject(deepLinkInfo);
        String submit_url = deepLinkInfoObj.getString("submit_url");

        JSONObject submitDataObj = deepLinkInfoObj.getJSONObject("submit_data");

        String charset = submitDataObj.getString("charset");

        String biz_content = submitDataObj.getString("biz_content");
        String method = submitDataObj.getString("method");
        String sign = submitDataObj.getString("sign");
        String return_url = submitDataObj.getString("return_url");
        String notify_url = submitDataObj.getString("notify_url");
        String app_id = submitDataObj.getString("app_id");
        String sign_type = submitDataObj.getString("sign_type");
        String version = submitDataObj.getString("version");
        String timestamp = submitDataObj.getString("timestamp");

        biz_content = biz_content.replace("&quot;", "\"");
        FormBody body = new FormBody.Builder()
                .add("charset", charset)
                .add("biz_content", biz_content)
                .add("method", method)
                .add("sign", sign)
                .add("return_url", return_url)
                .add("notify_url", notify_url)
                .add("app_id", app_id)
                .add("sign_type", sign_type)
                .add("version", version)
                .add("timestamp", timestamp)
                .build();

        Request request = new Request.Builder().post(body).url(submit_url)
//				.addHeader("Host", "openapi.alipay.com")
//				.addHeader("Content-Type", "application/x-www-form-urlencoded")
//				.addHeader("Cache-Control", "max-age=0")
//				.addHeader("Content-Length", "1190")
                .build();
        //禁止重定向，否则响应头中获取不到Location(支付链接)
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .followRedirects(false)
                .followSslRedirects(false)
                .build();
        try {
            Response execute = okHttpClient.newCall(request).execute();
            Headers headers = execute.headers();
            String location = headers.get("Location");
            if (location == null || location.equals("")) {
                log("获取支付链接失败");
                return;
            }
            log("获取支付链接成功：\n" + location);
            ClipboardUtils.copyText(location);
            log("支付链接已复制到粘贴板");
            Intent intent = new Intent();
            intent.setAction("android.intent.action.VIEW");
            Uri content_url = Uri.parse(location);
            intent.setData(content_url);
            ActivityUtils.startActivity(intent);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private static void log(Object obj) {
        Log.e(TAG, obj + "");
        EventBus.getDefault().post(obj.toString());
    }

    private static final String TAG = "youzanmeiye";
}
